<?php

class ProfileController extends Zend_Controller_Action
{
    public function init()
    {
		$auth = Zend_Auth::getInstance();

		if ( !$auth->hasIdentity() ) $this->_redirect('/auth');

		$this->usr = $this->view->usr = $auth->getIdentity();

		$this->db 	= Zend_Registry::get('db');
    }

    public function indexAction()
    {
    	$this->db->setFetchMode(Zend_Db::FETCH_OBJ);

    	$this->usr = $this->view->usr = $this->db->fetchRow('
    											SELECT
													Id,
													Locale,
													Privacy,
													Home
    											FROM
    												Usrs
    											WHERE
    												Id = ?', $this->usr->Id );

    	if ( !$this->usr->Home ){

    		if ( isset($_COOKIE['LL']) ){

	    		$this->view->LL = $this->db->fetchOne("
    													SELECT
    														CONCAT( Locality,', ', Country )
    													FROM
    														Lctns
    													WHERE
    														Id = ?", $_COOKIE['LL'] );
    		}
    	}else{
    		$this->view->HomeSet = true;
    	}

    	if ( $this->getRequest()->isPost() ){

    		$data = array();

			$this->usr->Locale 	= $data['Locale'] 	= $this->_getParam('Locale');
			$this->usr->Privacy	= $data['Privacy'] 	= $this->_getParam('Privacy');

			if ( $this->_getParam('Home') ){
				$this->usr->Home = $data['Home'] = (int)$this->_getParam('Home');
				$this->view->HomeSet = true;
			}

			$this->db->update( 'Usrs', $data, 'Id = '. $this->usr->Id );

    		// Updating Identity

    		$auth = Zend_Auth::getInstance();

    		$auth->getStorage()->write($this->usr);
    	}
    }
}